using System.Text;
using Gateway.Common.Enums;
using Gateway.Common.Models;
using Gateway.IQuery;
using Gateway.IQuery.Sign.Result;
using Gateway.IQuery.User;
using Gateway.IQuery.User.Request;
using Gateway.IQuery.User.Result;
using Gateway.IRepositories;
using Gateway.SqlSugar;

namespace Gateway.Query;

/// <summary>
/// 
/// </summary>
public class UserQuery : IUserQuery
{
    private readonly IQueryRepository _repository;

    /// <summary>
    /// 
    /// </summary>
    /// <param name="repository"></param>
    public UserQuery(IQueryRepository repository)
    {
        _repository = repository;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="request"></param>
    /// <returns></returns>
    public async Task<PageResult<UserDetailResult>> GetPageList(UserPageListRequest request)
    {
        StringBuilder where = new StringBuilder(100);
        SugarParameters parameters = new SugarParameters();
        if (!string.IsNullOrEmpty(request.Keywoard))
        {
            where.Append(" AND ( ");
            where.Append("  p.UserName like @keywoard ");
            where.Append(" or   p.Account like @keywoard ");
            where.Append(" ) ");
            parameters.Add("@keywoard", $"%{request.Keywoard}%");
        }

        if (request?.DepartmentIds?.Count > 0)
        {
            where.Append(
                $" AND p.DepartmentId in ({(string.Join(",", request.DepartmentIds.Select(p => "'" + p + "'")))}) ");
        }

        int count = 0;
        if (request.Page == 1)
        {
            count = await _repository.QueryFirstOrDefaultAsync<int>(
                $@"select count(1) from  User p where Deleted='N' {where.ToString()}", parameters);
        }

        string sql =
            $@"select userid, useravatar, username, account, userno, roleids, departmentid, createdtime, lastmodifiedtime, disabled from  User p where Deleted='N'
{where.ToString()}
order by  UserId,CreatedTime
limit  {request.Offset},{request.PageSize}";
        var data = await _repository.QueryListAsync<UserDetailResult>(sql, parameters);

        return PageResult<UserDetailResult>.Create(data, count);
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="userIds"></param>
    /// <returns></returns>
    public async Task<List<UserDetailResult>> GetUserByUserIds(List<string> userIds)
    {
        var data = await _repository.GetListAsync<UserDetailResult>(x => x.Disabled == BooleanStatusEnum.No.Value && userIds.Contains(x.UserId));
        return data;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <returns></returns>
    public async Task<List<string>> GetAllUserId()
    {
        var data = await _repository.GetListAsync<UserDetailResult>(x => x.Disabled == BooleanStatusEnum.No.Value);
        return data.Select(x => x.UserId).ToList();
    }


    /// <summary>
    ///  获取用的登录信息
    /// </summary>
    /// <param name="userId">用户标识</param>
    /// <returns></returns>
    /// <exception cref="MyException"></exception>
    public async Task<LoginUserInfoResult> GetUserLoginInfo(string userId)
    {
        var sql =
            @"select userid, useravatar, username, account, userno, roleids, departmentid from  User where UserId=@userId  and Deleted='N' and Disabled='N'";
        var data = await _repository.QueryFirstOrDefaultAsync<UserDetailResult>(sql, new
        {
            userId
        });
        if (data == null)
            throw new MyException("用户不存在");
        var result = new LoginUserInfoResult()
        {
            RoleIds = data.RoleIds,
            UserId = data.UserId,
            UserName = data.UserName,
            Account = data.Account
        };

        return result;
    }
}